/*上传*/

#include "threadPool.h"

int recvn(int sockfd, void *buf, int length)
{
    int total = 0;
    int ret;
    char *p = (char *)buf;
    while (total < length)
    {
        ret = recv(sockfd, p + total, length - total, 0);
        total += ret;
    }
    return 0;
}

int recvFile(int netfd, char *filename, off_t offset)
{
    char oriFilename[50] = {0};
    strcpy(oriFilename, filename);

    train_t train;
    bzero(&train, sizeof(train));
    strcat(filename, ".filepart");
    int fd = open(filename, O_RDWR | O_CREAT, 0666);
    lseek(fd, offset, SEEK_SET);
    off_t filesize;
    bzero(&train, sizeof(train));
    recvn(netfd, &train.length, sizeof(train.length));
    recvn(netfd, &filesize, train.length);
    printf("filesize = %ld\n", filesize);
    off_t cursize = 0;
    off_t lastsize = 0;
    off_t slice = filesize / 10000;
    while (1)
    {
        bzero(&train, sizeof(train));
        // recv(netfd,&train.length,sizeof(train.length),MSG_WAITALL);//先收四个字节
        recvn(netfd, &train.length, sizeof(train.length)); // 先收四个字节
        if (train.length != 1000)
        {
            printf("train.length = %d\n", train.length);
        }
        if (train.length == 0)
        {
            break;
        }
        // recv(netfd,train.data,train.length,MSG_WAITALL);//再一个train.length的长度
        recvn(netfd, train.data, train.length); // 再一个train.length的长度
        write(fd, train.data, train.length);
        cursize += train.length;
        if (cursize - lastsize > slice)
        {
            printf("%5.2lf%%\r", 100.0 * cursize / filesize);
            fflush(stdout);
            lastsize = cursize;
        }
    }
    printf("100.00%%\n");
    rename(filename, oriFilename);
    close(fd);
    return 0;
}